import Taro, { request as _request, uploadFile as _uploadFile, downloadFile as _downloadFile, showToast as _showToast } from "@tarojs/taro-h5";
import Store from '../store/index';
import { getCurrentPageUrlWithArgs, redirectToPage } from "./index";
/**
 * http请求
 */
// get请求
const get = async (apiPath, data) => {
  let apiRs = await apiRequest('GET', apiPath, 'application/json', data);
  return bizExect(apiRs, apiPath);
}; // post表单请求
const postForm = async (apiPath, data) => {
  let apiRs = await apiRequest('POST', apiPath, 'application/x-www-form-urlencoded', data);
  return bizExect(apiRs, apiPath);
};
// postJSON请求
const postJson = async (apiPath, data) => {
  let apiRs = await apiRequest('POST', apiPath, 'application/json', data);
  return bizExect(apiRs, apiPath);
};
// 上传文件请求
const uploadFile = async (apiPath, data) => {
  let apiRs = await apiRequest('POST', apiPath, 'multipart/form-data', data, 'uploadFile');
  return bizExect(apiRs, apiPath);
};
// 下载文件请求
const downloadFile = async (apiPath, data) => {
  let apiRs = await apiRequest('GET', apiPath, 'application/json', data, 'downloadFile');
  return bizExect(apiRs, apiPath);
};
// 请求方式处理
const apiRequest = async (method, apiPath, contenType, data, fileType) => {
  if (Store.stopReq) {
    return {
      httpCode: 423,
      code: 423,
      msg: '正在登录中，放弃当前请求！',
      data: null,
      next: true
    };
  }
  const url = getApiUrl(apiPath);
  if (fileType === 'uploadFile') {
    return await appUploadFile(method, url, contenType, data);
  } else if (fileType === 'downloadFile') {
    return await appDownloadFile(method, url, contenType, data);
  } else {
    return await appRequest(method, url, contenType, data);
  }
};
// 处理接口地址
const getApiUrl = apiPath => {
  // @ts-ignore
  const baseUrl = APIDOMIANS;
  return `${baseUrl}/${apiPath}`;
};
// 处理普通请求
const appRequest = async (method, url, contenType, data) => {
  const params = {
    url,
    data,
    header: getApiHeader(contenType),
    method
  };
  let wpRes = await _request(params).catch(ex => {
    if (ex && ex.errMsg == 'request:fail url not in domain list') {
      return {
        statusCode: 500,
        domainerror: true
      };
    } else if (ex && ex.errMsg && ex.errMsg.indexOf('request:fail') > -1) {
      console.log(506, ex);
      return {
        statusCode: 506
      };
    } else {
      throw ex;
    }
  });
  let res = wpRes.data;
  if (res) {
    res.httpCode = wpRes.statusCode;
    res.next = true;
  } else {
    res = {
      httpCode: wpRes.statusCode,
      code: wpRes.statusCode,
      data: null,
      next: true,
      domainerror: wpRes.domainerror
    };
  }
  return res;
};
// 处理上传请求
const appUploadFile = async (method, url, contenType, data) => {
  const params = {
    url,
    filePath: data.filePath,
    name: data.name,
    formData: data.formData,
    header: getApiHeader(contenType),
    method
  };
  let wpRes = await _uploadFile(params);
  let res = wpRes.data;
  let Res;
  if (res) {
    Res = {
      httpCode: wpRes.statusCode,
      next: true,
      data: res
    };
  } else {
    Res = {
      httpCode: wpRes.statusCode,
      code: wpRes.statusCode,
      data: null,
      next: true
    };
  }
  return Res;
};
// 处理下载请求
const appDownloadFile = async (method, url, contenType, data) => {
  const params = {
    url,
    header: getApiHeader(contenType),
    filePath: data.filePath,
    method
  };
  let wpRes = await _downloadFile(params);
  // let res = wpRes['data']
  // if (res) {
  //   res.httpCode = wpRes.statusCode
  //   res.next = true
  // } else {
  //   res = {
  //     httpCode: wpRes.statusCode,
  //     code: wpRes.statusCode,
  //     data: null,
  //     next: true
  //   }
  // }
  let res = {
    httpCode: wpRes.statusCode,
    code: wpRes.statusCode,
    next: true
  };
  return res;
};
// 处理公共请求头
const getApiHeader = contenType => {
  return {
    'Content-Type': contenType,
    'From': Store.model,
    'Authorization': 'Bearer ' + Store.jwtToken // 令牌
  };
};
// 校验
const bizExect = (apiRs, apiPath) => {
  apiRs.apiPath = apiPath;
  if (apiRs.domainerror) {
    apiRs.next = false;
    _showToast({ title: '请求域名配置错误' });
  } else if (apiRs.httpCode === 423) {
    apiRs.next = false;
    _showToast({ title: '正在登录中，放弃当前请求！' });
  } else if (apiRs.httpCode === 403) {
    // 服务器拒绝，未登录或账号过期
    apiRs.next = false;
    const returnUrl = getCurrentPageUrlWithArgs(); // 保存页面
    redirectToPage(`/pages/login/index?returnUrl=${escape(returnUrl)}`);
  }
  return apiRs;
};
export { get, postForm, postJson, uploadFile, downloadFile };